package cn.kgc.filter;


import cn.kgc.common.BaseContext;
import cn.kgc.common.R;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")  //过滤器名字和 拦截路径 （“/*” 全部）
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;  //向下转型
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的url
        String requestURI = request.getRequestURI();


            //创建一个数组（把不许要判断的放在这个数组里）
        String[] urls = new String[]{
                "/employee/login",        //登录按钮
                "/employee/logout",         //退出按钮
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        //2.判断本次请求是否需要处理（判断用户是否已经登录）
        boolean check = check(urls, requestURI);


        //3. 如果不需要处理则直接放行
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        //4-1.判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("employee") != null){

        Long empId= (Long) request.getSession().getAttribute("employee");       //session 里的值拿出来
            BaseContext.setCurrentId(empId);                                       //放到 ThreadLocal 里

            filterChain.doFilter(request,response);
            return;
        }

        //4-2.判断登录状态，如果已登录，则直接放行 --短信登录
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id 为{}",request.getSession().getAttribute("user"));
            Long UserId= (Long) request.getSession().getAttribute("user");       //session 里的值拿出来
            BaseContext.setCurrentId(UserId);                                       //放到 ThreadLocal 里

            filterChain.doFilter(request,response);
            return;
        }


        //5.如果未登录则显示登录结果通过输出流的方式向客户端页面相应数据
        response.getWriter().write(JSON.toJSONString(R.success("NOTLOGIN")));  //包装成JSON给前端发消息
        return;



    }

    /**
     * 请求地址和 不需要处理的地址做判断
     * @param urls
     * @param requestURI
     * @return
     */

    public boolean check(String[] urls, String requestURI){
       // 把 URL遍历出来
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);   //遍历出来的URL跟请求地址做比较
            if (match){  //如果等于true 则直接放行
                return true;
            }
        }

        return false;
    }
}
